package org.darkforest.admin.controller;

import org.darkforest.common.services.*;
import org.darkforest.common.util.JSONUtils;
import org.darkforest.common.util.Utils;
import org.darkforest.dao.mapper.AreaMapper;
import org.darkforest.dao.mapper.CountySupportPoorMapper;
import org.darkforest.dao.mapper.EnumParamMapper;
import org.darkforest.dao.mapper.GoodsClassMapper;
import org.darkforest.dao.mapper.GoodsCommonMapper;
import org.darkforest.model.*;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.StoreClassVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;

/**
 * 自营店铺管理
 * Created by admin on 2015/9/6.
 */
@Controller
@RequestMapping("store")
public class StoreSelfSupportingController {


    @Autowired
    private StoreService storeService;

    @Autowired
    private SellerService sellerService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private StoreSelfSupportingService storeSelfSupportingService;

    @Autowired
    private StoreBindClassService storeBindClassService;

    @Autowired
    private GoodsClassRedisService goodsClassRedisService;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private StoreClassService storeClassService;
    @Autowired
    private GoodsClassMapper goodsClassMapper;
    @Autowired
    private StoreJoinInService storeJoinInService;
    @Autowired
    private EnumParamMapper enumParamMapper;
    @Autowired
    private GoodsCommonMapper goodsCommonMapper;
    @Autowired
    private CountySupportPoorMapper countySupportPoorMapper;

    /**
     * 自营店铺管理列表
     * @param start
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList")
    public ModelAndView selfSupportingStoreList(@RequestParam(required = false, defaultValue = "1") int start,
                                                @RequestParam(required = false, defaultValue = "") String storeName){
        Store store = new Store();
//        store.setIsOwnShop(1);
        store.setStart(start);
        if(!"".equals(storeName)){
            store.setStoreName(storeName);
        }
        store =  storeService.findStoreByPage(store);
        ModelAndView res = new ModelAndView("store/selfsupporting/self_supporting_list");
        res.addObject("page",store);
        return res;

    }


    /**
     * 跳转到新增自营店铺页面
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/toAddSelfSupporting")
    public ModelAndView toAddSelfSupporting(){
        ModelAndView res = new ModelAndView("store/selfsupporting/add_self_supporting");
        List<Area>  areas = areaMapper.getAreaListByParentId(0);
        res.addObject("areas",areas);
        StoreClass storeClass = new StoreClass();
        storeClass.setPageSwitch(false);
        res.addObject("storeClasses", storeClassService.selectListByCondition(storeClass));
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcParentId(0);
        List<GoodsClass> goodsClasss= goodsClassMapper.findGoodsClass(goodsClass);
        res.addObject("goodsClasss", goodsClasss);//商品分类

        EnumParam enumParam = new EnumParam();
        enumParam.setPageSwitch(false);
        enumParam.setParamType("company");
        enumParam.setParamState(1);
        List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
        res.addObject("enumParams", list);
//        enumParam.setParamType("county");
//        List<EnumParam> list2 = enumParamMapper.selectListByCondition(enumParam);
        CountySupportPoor countySupportPoor = new CountySupportPoor();
        countySupportPoor.setPageSwitch(false);
        List<CountySupportPoor> countyList = countySupportPoorMapper.selectListByCondition(countySupportPoor);
        res.addObject("countyList", countyList);
        return  res;
    }




    /**
     * 添加时校验是否存在以下
     * @param store_name
     * @param member_name
     * @param seller_name
     * @return
     */
    @RequestMapping(value = "checkSelfSupporting")
    public @ResponseBody boolean checkSelfSupporting(@RequestParam(required = false, defaultValue = "") String store_name,
                                                     @RequestParam(required = false, defaultValue = "") String member_name,
                                                     @RequestParam(required = false, defaultValue = "") String seller_name){
        boolean result = true;
        if(!"".equals(store_name)){
            Store store = new Store();
            store.setStoreNameEq(store_name);
            List<Store> storeList = storeService.findStoreByCondition(store);
            if(storeList.size()>0) {
                result= false;
            }else{
                result= true;
            }

        }
        if(!"".equals(member_name)){
            Member member = new Member();
            member.setMemberName(member_name);

            List<Member> memberList = memberService.getMemberInfoByCond(member);
            if(memberList.size()>0) {
                result= false;
            }else{
                result= true;
            }
        }
        if(!"".equals(seller_name)){
            Seller seller = new Seller();
            seller.setSellerName(seller_name);
            List<Seller>  sellerList = sellerService.findSellerByCondition(seller);
            if(sellerList.size()>0) {
                result= false;
            }else{
                result= true;
            }
        }

        return result;

    }


    /**
     * 新增自营店铺
     * @param storeInfo
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/doAddSelfSupporting")
    public ModelAndView doAddSelfSupporting(@ModelAttribute("store") Store storeInfo ){
        if (storeInfo.getToreClassVos() != null && storeInfo.getToreClassVos().length > 0) {
            List<StoreClassVo> list = new ArrayList<StoreClassVo>(storeInfo.getToreClassVos().length);
            for (int i = 0; i < storeInfo.getToreClassVos().length; i++) {
                list.add(storeInfo.getToreClassVos()[i]);
            }
            for (int j = 0; j < list.size(); j++) {
                StoreClassVo storeClassVo = list.get(j);
                if (storeClassVo.getStoreClassId() == null || "".equals(storeClassVo.getStoreClassId())) {
                    list.remove(j);
                    j--;
                }
            }
            StoreClassVo[] storeClassVos = list.toArray(new StoreClassVo[list.size()]);
            storeInfo.setToreClassVos(storeClassVos);
        }
        storeSelfSupportingService.addSelfSupporting(storeInfo);
//        return "redirect: selfSupportingStoreList";
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "自营店铺新增成功");
        modelAndView.addObject("returnUrl", "store/selfSupportingStoreList");
        return modelAndView;
    }

    /**
     * 删除自营店铺
     * @param storeId
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/delSelfSupporting")
    public ModelAndView delSelfSupporting(Integer storeId){
        storeSelfSupportingService.delSelfSupportingByStoreId(storeId);
//        return "redirect: selfSupportingStoreList";
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "自营店铺删除成功");
        modelAndView.addObject("returnUrl", "store/selfSupportingStoreList");
        return modelAndView;
    }

    /**
     * 跳转到编辑自营店铺页面
     * @param storeId
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/toModifySelfSupporting")
    public ModelAndView toModifySelfSupporting(Integer storeId){
        ModelAndView res = new ModelAndView("store/selfsupporting/modify_self_supporting");
        Store store = storeService.selectStoreByPrimaryKey(storeId);
        res.addObject("store", store);
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcParentId(0);
        List<GoodsClass> goodsClasss= goodsClassMapper.findGoodsClass(goodsClass);
        res.addObject("goodsClasss", goodsClasss);//商品分类
        StoreJoinIn storeJoinin = storeJoinInService.selectByPrimaryKey(store.getMemberId());
        if(storeJoinin.getStoreClassIds()!= null){
            List<StoreClassVo> list= JSONUtils.toList(storeJoinin.getStoreClassIds(), StoreClassVo.class);
            res.addObject("storeClassList", list);
        }

        //获取贫困县或者企业
        EnumParam enumParam = new EnumParam();
        enumParam.setPageSwitch(false);
        enumParam.setParamType("company");
        enumParam.setParamState(1);
        List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
        res.addObject("enumParams", list);
//        enumParam.setParamType("county");
//        List<EnumParam> list2 = enumParamMapper.selectListByCondition(enumParam);
        CountySupportPoor countySupportPoor = new CountySupportPoor();
        countySupportPoor.setPageSwitch(false);
        List<CountySupportPoor> countyList = countySupportPoorMapper.selectListByCondition(countySupportPoor);
        res.addObject("countyList", countyList);
        StoreClass storeClass = new StoreClass();
        storeClass.setPageSwitch(false);
        res.addObject("storeClasses", storeClassService.selectListByCondition(storeClass));
        return res;

    }

    /**
     * 编辑自营店铺
     * @param storeInfo
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/doModifySelfSupporting")
    public ModelAndView doModifySelfSupporting(@ModelAttribute("store") StoreWithBLOBs storeInfo){
        if (storeInfo.getToreClassVos() != null && storeInfo.getToreClassVos().length > 0) {
            List<StoreClassVo> list = new ArrayList<StoreClassVo>(storeInfo.getToreClassVos().length);
            for (int i = 0; i < storeInfo.getToreClassVos().length; i++) {
                list.add(storeInfo.getToreClassVos()[i]);
            }
            for (int j = 0; j < list.size(); j++) {
                StoreClassVo storeClassVo = list.get(j);
                if (storeClassVo.getStoreClassId() == null || "".equals(storeClassVo.getStoreClassId())) {
                    list.remove(j);
                    j--;
                }
            }
            StoreClassVo[] storeClassVos = list.toArray(new StoreClassVo[list.size()]);
            storeInfo.setToreClassVos(storeClassVos);
        }
        storeService.modifyStore(storeInfo);
//        return "redirect:selfSupportingStoreList";
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "自营店铺编辑成功");
        modelAndView.addObject("returnUrl", "store/selfSupportingStoreList");
        return modelAndView;
    }

    @RequestMapping(value = "checkStoreClass")
    public @ResponseBody boolean checkStoreClass(Integer storeId, Integer storeClassId){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("storeId",storeId);
        map.put("storeClassId",storeClassId);
        Integer result = goodsCommonMapper.getGoodsNumByClassId(map);
        if (result > 0) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "checkWhenModify")
    public  @ResponseBody boolean checkWhenModify(Integer store_id,String columnName,String columnVal){

        boolean result = true;
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("storeId",store_id);
        map.put("columnName",columnName);
        map.put("columnVal",columnVal);
        if("store_name".equals(columnName)){
            List<Store> storeList = storeService.findStoreExceptSelf(map);
            if(storeList.size()>0){
                result = false;
            }
        }

        if("seller_name".equals(columnName)){
            List<Seller> sellerList = sellerService.findSellerExceptSelf(map);
            if(sellerList.size()>0){
                result = false;
            }
        }


        return result;

    }

    /**
     * 跳转到店铺经营条目页面
     * @param storeId
     * @return
     */
    @RequestMapping(value = "selfSupportingStoreList/toManagerOperateType")
    public ModelAndView toManagerOperateType(Integer storeId,
                                             String storeName,
                                             @RequestParam(required = false, defaultValue = "1") int start){
        ModelAndView res = new ModelAndView("store/selfsupporting/self_supporting_operate");
        StoreBindClass storeBindClass = new StoreBindClass();
        storeBindClass.setStoreId(storeId);
        storeBindClass.setStart(start);
        storeBindClass.setPageSize(5);
        storeBindClass  = storeBindClassService.selectStoreBindClassListByPage(storeBindClass);
        List<GoodsClass> goodsClassList = goodsClassRedisService.getGoodsClassList(null);

        res.addObject("page",storeBindClass);
        res.addObject("storeName",org.apache.commons.lang.StringUtils.isEmpty(storeName) ? null : Utils.encodeGetParam(storeName));
        res.addObject("goodsClassList",goodsClassList);
        return res;

    }


    @RequestMapping(value = "doManagerOperateType")
    public String doManagerOperateType(Integer storeId,String goodsClass,String commisRate){

        String[] goodsClasses = goodsClass.split(",");
        StoreBindClass storeBindClass = new StoreBindClass();
        storeBindClass.setStoreId(storeId);
        storeBindClass.setClass1(Integer.parseInt(goodsClasses[0]));
        storeBindClass.setClass2(Integer.parseInt(goodsClasses[1]));
        storeBindClass.setClass3(Integer.parseInt(goodsClasses[2]));
        storeBindClass.setCommisRate(new BigDecimal(commisRate));

        int i = storeBindClassService.addStoreBindStoreGoodsClass(storeBindClass);

        return "redirect: /selfSupportingStoreList/toManagerOperateType?storeId="+storeId;
    }

    @RequestMapping(value = "updateStoreBindClassCommisRate")
    public @ResponseBody
    AjaxReturnData updateStoreBindClassCommisRate(Integer id,Integer value){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        if(value>=0 && value<=100){
            try{
                StoreBindClass storeBindClass = new StoreBindClass();
                storeBindClass.setBid(id);
                storeBindClass.setCommisRate(new BigDecimal(value));

                int i = storeBindClassService.updateByPrimaryKeySelective(storeBindClass);
                if(i==1){
                    ajaxReturnData.setResult(true);
                }else{
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("影响条数："+i);
                }
            }catch (Exception e){
                ajaxReturnData.setMessage("参数异常"+e);
                ajaxReturnData.setResult(false);
            }
        }else{
            ajaxReturnData.setMessage("分佣比例必须为0-100的整数");
            ajaxReturnData.setResult(false);
        }

        return ajaxReturnData;
    }


    /**
     * 批量删除
     * @param ids
     * @param storeId
     * @return
     */
    @RequestMapping(value = "deleteStoreBindClassBatch")
    public String deleteStoreBindClassBatch(String[] ids,Integer storeId){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        ajaxReturnData.setResult(true);
        try{
            storeBindClassService.soldOutStoreGoods(ids,storeId);
        }catch (Exception e){
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("删除异常"+e);
        }
        return "redirect: selfSupportingStoreList/toManagerOperateType?storeId="+storeId;

    }

    /**
     * 单条删除
     * @param ids
     * @param storeId
     * @return
     */
    @RequestMapping(value = "deleteStoreBindClassSingle")
    public @ResponseBody AjaxReturnData deleteStoreBindClassSingle(String[] ids,Integer storeId){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        ajaxReturnData.setResult(true);
        try{
            storeBindClassService.soldOutStoreGoods(ids,storeId);
        }catch (Exception e){
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("删除异常"+e);
        }


        return ajaxReturnData;

    }
}